<!--

/*#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code is not supported by Google
#
*/
-->

<!--
Sample .jsp code for Google Commerce Search showing GCS product recommendations.

see:
https://developers.google.com/commerce-search/docs/recommendations/gcs_recommendations
-->

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import='java.util.*' %>
<%@ page import='java.io.*' %>
<%@ page import='java.net.*' %>
<%@ page import='javax.xml.parsers.*' %>
<%@ page import='org.w3c.dom.*' %>
<%@ page import='org.xml.sax.*' %>
<%@ page import='java.util.regex.*' %>
<%@ page import='javax.xml.xpath.*' %>
<%@ page import='javax.xml.namespace.*' %>
<%@ page import='javax.xml.parsers.*' %>


<%!
public enum Offer_TYPE {OFFER, RECOMMENDATION;}

final class Offer
{
    private String title;
    private String link;
    private String image;
    private String offer_id;
    private String google_id;
    
    public Offer(String title, String link, String image, String offer_id, String google_id) 
    {
        this.title = title;
        this.link = link;
        this.image = image;
		this.offer_id = offer_id;
		this.google_id = google_id;
    }
}
%>

<%
String cx  = request.getParameter("cx");
String cid  = request.getParameter("cid");
String offer_id  = request.getParameter("offerid");
String key = "<YOUR_KEY>";

String error = "";


if (cx == null || cid == null || offer_id == null || cx.isEmpty() || cid.isEmpty() || offer_id.isEmpty()) {
	error = "(using default values for  cx, cid, offer_id )";
	cx = "005865242780510660151:o9vudkrzvj8";
	cid = "1004539";
	offer_id="online:en:us:261703";
}

String shopping_base_query = "https://www.googleapis.com/shopping/search/v1/cx:" + cx + "/products/" + cid +  "/pid/" + offer_id + "?alt=atom&key=" + key;

Offer curr = null;
try {
	 ArrayList<Offer> al_offer = processResponse(shopping_base_query, Offer_TYPE.OFFER);
	 if (al_offer.size()>0)
	    curr = al_offer.get(0);
}
catch (Exception ex){
	    error +=  "<br/>" + "Error Recalling Offer " + ex.toString();	
		System.out.println("err: " + ex);
}


ArrayList<Offer> al_visittovisit = null;
ArrayList<Offer> al_visittopurchase = null;
ArrayList<Offer> al_purchasetopurchase = null;
ArrayList<Offer> al_relatedItems = null;


String visitToVisit_query =	shopping_base_query + "&recommendations.enabled=true&recommendations.include=visitToVisit:3&recommendations.useGcsConfig=true";
String visitToPurchase_query =	shopping_base_query + "&recommendations.enabled=true&recommendations.include=visitToPurchase:3&recommendations.useGcsConfig=true";
String purchaseToPurchase_query =	shopping_base_query + "&recommendations.enabled=true&recommendations.include=purchaseToPurchase:3&recommendations.useGcsConfig=true";
String relatedItems_query =	shopping_base_query + "&recommendations.enabled=true&recommendations.include=relatedItems:3&recommendations.useGcsConfig=true";


if (curr != null){
	try {
		//NOTE:  you can combine all the requests together:
			//&recommendations.include=visitToVisit:3,purchaseToPurchase:3
		al_visittovisit = processResponse(visitToVisit_query, Offer_TYPE.RECOMMENDATION);
		al_visittopurchase = processResponse(visitToPurchase_query, Offer_TYPE.RECOMMENDATION);	
		al_purchasetopurchase = processResponse(purchaseToPurchase_query, Offer_TYPE.RECOMMENDATION);	
		al_relatedItems = processResponse(relatedItems_query, Offer_TYPE.RECOMMENDATION);			
	}
	catch (Exception ex){
			error +=  "<br/>" + "Error Recalling Recommendations: " + ex.toString();
			System.out.println("Error Recalling Recommendations: " + ex);
	}
}

//now create the request without the offer_id
String qrewrite = "view_recommendations.jsp?cx="+ cx + "&cid=" + cid + "&offerid=" ;
if (offer_id.split(":").length!=4)
{
	error = "(offer_id must be online:lang:country:your_offer_id (online:en:us:261703))";
	offer_id="online:en:us:261703";
}
else {
	String[] offer_id_array = offer_id.split(":");
	qrewrite = qrewrite + offer_id_array[0] +":"+ offer_id_array[1] + ":" + offer_id_array[2];
}


%>

<%!
private ArrayList<Offer> processResponse(String u, Offer_TYPE type) throws Exception
{

	    URL url = new URL(u);
 	    Date starttime = new Date();
	    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
	    InputStream inputStream = httpConnection.getInputStream();

	    DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
	    DocumentBuilder docBuilder = (DocumentBuilder) docBF.newDocumentBuilder();
	    Document doc = docBuilder.parse(inputStream);
	    doc.getDocumentElement().normalize();
	    
	    // TODO: refactor with namespace aware context:
	    //docBF.setNamespaceAware(true);
	    //Node n_results = (Node) xpath.evaluate("/atom:feed/openSearch:totalResults", doc, XPathConstants.NODE);
	    

		NamespaceContext ctx = new NamespaceContext()
		{
			public String getNamespaceURI(String prefix) {
				String uri;
				if (prefix.equals("openSearch"))
					uri = "http://a9.com/-/spec/opensearchrss/1.0/";
				else if (prefix.equals("s"))
					uri = "http://www.google.com/shopping/api/schemas/2010";
				else if (prefix.equals("gd"))
					uri = "http://schemas.google.com/g/2005";
				else if (prefix.equals("atom"))
					uri = "http://www.w3.org/2005/Atom";
				else
					uri = null;
				return uri;
			}
			public Iterator getPrefixes(String val) {
				return null;
			}         
			public String getPrefix(String uri) {
				return null;
			}
		};

        XPathFactory xpathFactory = XPathFactory.newInstance();
	    XPath xpath = xpathFactory.newXPath();
	    xpath.setNamespaceContext(ctx);

	   ArrayList<Offer> ret_offers = new ArrayList<Offer>();
	   
	   if (type == Offer_TYPE.OFFER) {		   
	          Node n_offer = (Node) xpath.evaluate("/entry/product", doc, XPathConstants.NODE);
	          if (n_offer != null)
	          {
	        	Node n_googleID = (Node) xpath.evaluate("googleId", n_offer, XPathConstants.NODE);
	        	Node n_title = (Node) xpath.evaluate("title", n_offer, XPathConstants.NODE);
	        	Node n_link = (Node) xpath.evaluate("link", n_offer, XPathConstants.NODE);
	        	Node n_offer_id = (Node) xpath.evaluate("providedId", n_offer, XPathConstants.NODE);	        	
	        	Node n_image = (Node) xpath.evaluate("images/image", n_offer, XPathConstants.NODE);
	        	Offer curr = new Offer(n_title.getTextContent(),n_link.getTextContent(), n_image.getAttributes().getNamedItem("link").getNodeValue(),n_offer_id.getTextContent(), n_googleID.getTextContent());
	        	ret_offers.add(curr);
	          }
	   }
	   else {
	          NodeList nl_recs = (NodeList) xpath.evaluate("/entry/recommendations/recommendationList/recommendation/product", doc, XPathConstants.NODESET);
	          if (nl_recs != null)
	          {
				for (int i=0; i<nl_recs.getLength(); i++)
				{
					Node n_offer = nl_recs.item(i);
		        	Node n_googleID = (Node) xpath.evaluate("googleId", n_offer, XPathConstants.NODE);
		        	Node n_title = (Node) xpath.evaluate("title", n_offer, XPathConstants.NODE);
		        	Node n_link = (Node) xpath.evaluate("link", n_offer, XPathConstants.NODE);
		        	Node n_offer_id = (Node) xpath.evaluate("providedId", n_offer, XPathConstants.NODE);	        	
		        	Node n_image = (Node) xpath.evaluate("images/image", n_offer, XPathConstants.NODE);
		        	Offer curr = new Offer(n_title.getTextContent(),n_link.getTextContent(), n_image.getAttributes().getNamedItem("link").getNodeValue(),n_offer_id.getTextContent(), n_googleID.getTextContent());
		        	ret_offers.add(curr);										
				}
	          }
	   }
	   
	   return ret_offers; 	
}

%>


<html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <link rel="stylesheet" type="text/css" href="https://developers.google.com/css/screen.css" />
      <link href='//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>    
    </head>
    
    <body class="two-column docs">
    <div id="gc-wrapper">
    <div id="gc-main">
    <div id="gc-content">
    
	<img src="http://www.google.com/intl/en/images/logos/commerce_search_logo.gif" alt="Google Commerce Search"/>
	
	<p>
	Displays various Google Commerce Search Recommendations for a given offer.
	</p>

	<p class="note">
	<strong>NOTE: </strong> You must first configure <a href="https://developers.google.com/commerce-search/docs/recommendations/gcs_recommendations#analytics_rec">Google Analytics for Recommendations.</a>
	</p>
    <form id="searchForm" method="GET">
	    <table width="90%" border="1">
    		<tr><td>cx:</td><td><input id="cx" name="cx" type="text" size="45%" autocomplete="off" value ="<%=cx%>" /></td></tr>     
    		<tr><td>merchantID</td><td><input id="cid" name="cid" type="text" size="45%" autocomplete="off" value ="<%=cid%>" /></td></tr>         		
    		<tr><td>offerid</td><td><input id="offerid" name="offerid" type="text" size="45%" autocomplete="off" value ="<%=offer_id%>"/></td></tr>     
		</table>
		<p>
		<font color="red"><%=error%></font>
		</p>   
	    
		<input type="submit" value="Submit" "/>	
    </form>	
    
    <br/>
    <br/>
    
    <% if (curr !=null) {%>
    <h3>Offer</h3>
    <p>The current offer to get recommendations for.</p>
	<font size="1px">
		<a href='<%=shopping_base_query%>&prettyprint=true'><%=URLDecoder.decode(shopping_base_query,"UTF-8")%></a>
	</font>      
	<table width="90%" border="1">
      <tr>
       <th scope="col">Title</th>
       <th scope="col">offer_id</th>
       <th scope="col">google_id</th>     
      </tr>
      <tr>
        <td><center><a href="<%=curr.link %>"><img width="60" height="60" src="<%=curr.image %>"/><br/><%=curr.title %></a></center></td>
        <td><%=curr.offer_id %></td>
        <td><%=curr.google_id %></td>                
      </tr>
	</table>

	
	
    <h3>VisitToVisit</h3>
    <p>"Shoppers who viewed this item also viewed..."</p>
	<font size="1px">
		<a href='<%=visitToVisit_query%>&prettyprint=true'><%=URLDecoder.decode(visitToVisit_query,"UTF-8")%></a>
	</font>      
	<table width="90%" border="1">
      <tr>
       <th scope="col">Title</th>
       <th scope="col">offer_id</th>
       <th scope="col">google_id</th>     
      </tr>
      <% if (al_visittovisit != null) {
    	  for (Offer o: al_visittovisit) {
      %>
	      <tr>
	        <td><center><a href="<%=o.link %>"><img width="60" height="60" src="<%=o.image %>"/><br/><%=o.title %></a></center></td>
	        <td><a href="<%=qrewrite + ":" + o.offer_id%>"><%=o.offer_id %></a></td>
	        <td><%=o.google_id %></td>                
	      </tr>
      <%   } %>
      <% } %>
	</table>

	
    <h3>VisitToPurchase</h3>
    <p>"Shoppers who viewed this item also purchased..."</p>
	<font size="1px">
		<a href='<%=visitToPurchase_query%>&prettyprint=true'><%=URLDecoder.decode(visitToPurchase_query,"UTF-8")%></a>
	</font>      
	<table width="90%" border="1">
      <tr>
       <th scope="col">Title</th>
       <th scope="col">offer_id</th>
       <th scope="col">google_id</th>     
      </tr>
      <% if (al_visittopurchase != null) {
    	  for (Offer o: al_visittopurchase) {
      %>
	      <tr>
	        <td><center><a href="<%=o.link %>"><img width="60" height="60" src="<%=o.image %>"/><br/><%=o.title %></a></center></td>        
	        <td><a href="<%=qrewrite + ":" + o.offer_id%>"><%=o.offer_id %></a></td>
	        <td><%=o.google_id %></td>                
	      </tr>
      <%   } %>
      <% } %>
	</table>

	
	
    <h3>PurchaseToPurchase</h3>
    <p>"Shoppers who bought this item also bought..."</p>
	<font size="1px">
		<a href='<%=purchaseToPurchase_query%>&prettyprint=true'><%=URLDecoder.decode(purchaseToPurchase_query,"UTF-8")%></a>
	</font>  	    
	<table width="90%" border="1">
      <tr>
       <th scope="col">Title</th>
       <th scope="col">offer_id</th>
       <th scope="col">google_id</th>     
      </tr>
      <% if (al_purchasetopurchase != null) {
    	  for (Offer o: al_purchasetopurchase) {
      %>
	      <tr>
	        <td><center><a href="<%=o.link %>"><img width="60" height="60" src="<%=o.image %>"/><br/><%=o.title %></a></center></td>        
	        <td><a href="<%=qrewrite + ":" + o.offer_id%>"><%=o.offer_id %></a></td>
	        <td><%=o.google_id %></td>                
	      </tr>
      <%   } %>
      <% } %>
	</table>

		
	
    <h3>RelatedItems</h3>
    <p>Recommendations derived from other Google Properties</p>
	<font size="1px">
		<a href='<%=relatedItems_query%>&prettyprint=true'><%=URLDecoder.decode(relatedItems_query,"UTF-8")%></a>
	</font>	    
	<table width="90%" border="1">
      <tr>
       <th scope="col">Title</th>
       <th scope="col">offer_id</th>
       <th scope="col">google_id</th>     
      </tr>
      <% if (al_relatedItems != null) {
    	  for (Offer o: al_relatedItems) {
      %>
	      <tr>
	        <td><center><a href="<%=o.link %>"><img width="60" height="60" src="<%=o.image %>"/><br/><%=o.title %></a></center></td>    
	        <td><a href="<%=qrewrite + ":" + o.offer_id%>"><%=o.offer_id %></a></td>
	        <td><%=o.google_id %></td>                
	      </tr>
      <%   } %>
      <% } %>
	</table>

	<% } %>

    </div>
    </div>
    </div>

    </body>
    
</html>